﻿using CocoaAni.Net.WebSockets.Messages;
using CocoaAni.Net.WebSockets.Server.DefineInfos;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CocoaAni.Net.WebSockets.Server.ArgAdapters.Base;
public class MessageArgContext
{
    public MessageArgContext(WebSocketContext webSocketContext)
    {
        WebSocketContext = webSocketContext;
        ArgDefineInfo = null!;
    }

    public void SetNextArgInfo(HandlerArgDefineInfo argDefineInfo)
    {
        ArgDefineInfo=argDefineInfo;
    }

    public void Reset()
    {
        ArgDefineInfo = null!;
        _jsonObject = null;
        _isJsonObject = true;
    }

    private JObject? _jsonObject;
    private bool _isJsonObject = true;

    public WebSocketContext WebSocketContext { get; }
    public HandlerArgDefineInfo ArgDefineInfo { get; private set; }
    public Message Message => WebSocketContext.Message;
    public WebSocket Socket => WebSocketContext.Socket;

    public JsonReaderException? JsonException { get; private set; }

    public JObject? JsonObject
    {
        get
        {
            if (!_isJsonObject || !Message.IsText)
                return null;
            if (_jsonObject!=null)
                return _jsonObject;
            try
            {
                _jsonObject=JObject.Parse(Message.ToString());
            }
            catch (JsonReaderException e)
            {
                JsonException = e;
                _isJsonObject = false;
            }
            return _jsonObject;
        }
    }


}